import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import java.io.*;

@SuppressWarnings("serial")
public class FileAction extends ActionSupport {
    private File object;
    private String objectFileName;
    private String objectContentType;

    public File getObject() {
        return object;
    }

    public void setObject(File object) {
        this.object = object;
    }

    public String getObjectFileName() {
        return objectFileName;
    }

    public void setObjectFileName(String objectFileName) {
        this.objectFileName = objectFileName;
    }

    public String getObjectContentType() {
        return objectContentType;
    }

    public void setObjectContentType(String objectContentType) {
        this.objectContentType = objectContentType;
    }

    public InputStream getDownloadFileStream() throws FileNotFoundException, UnsupportedEncodingException {
        File directory = new File(ServletActionContext.getServletContext().getRealPath("/uploaded"));
        if (directory.exists() || directory.mkdirs()) {
            String downloadFilePath = directory + File.separator + getObjectFileName();
            return new FileInputStream(new String(downloadFilePath.getBytes(), "ISO-8859-1"));
        } else {
            return null;
        }
    }

    public File[] files() {
        File directory = new File(ServletActionContext.getServletContext().getRealPath("/uploaded"));
        return directory.exists() || directory.mkdirs() ? directory.listFiles() : null;
    }

    public String upload() {
        File directory = new File(ServletActionContext.getServletContext().getRealPath("/uploaded"));
        if (directory.exists() || directory.mkdirs()) {
            String uploadFilePath = directory.getPath() + File.separator + getObjectFileName();
            byte[] buffer = new byte[8192];
            int length;
            try (InputStream is = new FileInputStream(object); OutputStream os = new FileOutputStream(uploadFilePath)) {
                while ((length = is.read(buffer)) != -1) {
                    os.write(buffer, 0, length);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return INPUT;
            }
            return "upload";
        } else
            return null;
    }

    public String download() {
        return "download";
    }

    public String delete() {
        String deleteFilePath = ServletActionContext.getServletContext().getRealPath("/uploaded/") + getObjectFileName();
        File deleteFile = new File(deleteFilePath);
        if (deleteFile.delete())
            return "delete";
        return SUCCESS;
    }
}
